import {
  ProForm,
  ProFormText, ProFormTextArea,
  StepsForm,
  // @ts-ignore
} from '@ant-design/pro-components';
// @ts-ignore
import { message } from 'antd';
// @ts-ignore
import React, {useEffect, useState} from 'react';
import {addBookComment, getCurrentUserById} from "@/services/ant-design-pro/api";
import { history } from '@umijs/max'

interface IProps {
  book: API.BookDetail;
}
const CommentForm:React.FC<IProps> = ({book}) => {
  const Components = {
    ProForm,
    StepsForm,
  };
  const [type] = useState<keyof typeof Components>('ProForm');
  const FormComponents = Components[type];

  const [currentUser,setCurrentUser] = useState<API.CurrentUser>({})
  const getCurrentUser = async (userId: string) => {
    try {
      const res = await getCurrentUserById(userId);
      if (res.data) {
        setCurrentUser(res);
      }
    } catch (error) {
      console.log(error);
    }
  }
  useEffect(() => {
    if(localStorage.getItem("userId")){
      // @ts-ignore
      getCurrentUser(localStorage.getItem("userId")).then()
    }
  },[])


  const addComment = async (values:API.CommentParams) => {
    try {
      // @ts-ignore
      values.book_id = book.data.id
      values.picture = "https://gw.alipayobjects.com/zos/antfincdn/efFD%24IOql2/weixintupian_20170331104822.jpg"
      // @ts-ignore
      values.name = currentUser.data.username

      console.log(values)
      const res = await addBookComment(values);
      // @ts-ignore
      if (res.code === "200") {
        // @ts-ignore
        history.push(`/book/detail/${book.data.id}`);
      }
    } catch (error) {
      console.log(error);
    }
  }


  return (
    <>
      <FormComponents
        // @ts-ignore
        labelWidth="auto"
        onFinish={async (values: any) => {
          console.log(values);
          await addComment(values);
          message.success('提交成功');
        }}
      >

        <ProFormTextArea
          name="content"
          label="我的评论"
          placeholder="请输入评论"
          style={{
            width: "100%",
          }}
        />
        <ProFormText
          name="score"
          label="评分"
          style={{
            width: "100%",
          }}
          rules={[
            {
              validator: async (_, value) => {
                if (value === '') {
                  // 空值视为通过验证，允许清空输入
                  return Promise.resolve();
                }
                const regex = /^0+(\.([0-9])?)?|([1-9][0-9]?(\.[0-9])?)$/; // 正则表达式，匹配整数和小数
                if (!regex.test(value)) {
                  // 如果输入不符合数字格式，则返回错误信息
                  return Promise.reject(new Error('请输入有效评分'));
                }
                return Promise.resolve();
              },
            },
          ]}
          placeholder="请输入"
        />
      </FormComponents>
    </>
  );
};
export default CommentForm
